import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { ElMessage } from 'element-plus';
import { usePathConfigStore } from '@/stores/project/path-config';
import LoginView from '@/views/auth/LoginView.vue';
import RegisterView from '@/views/auth/RegisterView.vue';
import BackstageLayout from '@/components/layout/BackstageLayout.vue';
import FrontstageLayout from '@/components/layout/FrontstageLayout.vue';
import FrontView from '@/views/front/FrontView.vue';
import PackageView from '@/views/front/PackageView.vue';
import AnnouncementView from '@/views/front/AnnouncementView.vue';
import AnnouncementManage from '@/views/back/AnnouncementManage.vue';
import PackageManage from '@/views/back/PackageManage.vue';

const routes: Array<RouteRecordRaw> = [
  { path: '/', redirect: () => usePathConfigStore().getFrontstageHomePath },
  { path: '/login', name: 'LoginView', component: LoginView },
  { path: '/register', name: 'RegisterView', component: RegisterView },
  {
    path: '/front',
    component: FrontstageLayout,
    children: [
      { path: 'view', name: 'FrontView', component: FrontView },
      { path: 'package', name: 'PackageView', component: PackageView },
      { path: 'announcement', name: 'AnnouncementView', component: AnnouncementView },
    ],
  },
  {
    path: '/back', component: BackstageLayout, children: [
      {
        path: 'announcement', children: [
          { path: 'manage', name: 'AnnouncementManage', component: AnnouncementManage, },
        ],
      },
      {
        path: 'package', children: [
          { path: 'manage', name: 'PackageManage', component: PackageManage, },
        ],
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach(async (to, from, next) => {
  const { useUserStore } = await import('@/stores/api/user');
  const { usePathPermissionStore } = await import('@/stores/project/path-permission');

  const userStore = useUserStore();
  const permissionStore = usePathPermissionStore();

  // 检查是否访问后台页面
  if (to.path.startsWith('/back')) {
    if (!userStore.user) {
      ElMessage.error('请先登录');
      next({ path: '/login', query: { redirect: to.fullPath } });
      return;
    }
  }

  // 检查权限
  const userRole = userStore.user?.role || '';
  const forbiddenPaths = permissionStore.getForbiddenPaths(userRole);

  if (forbiddenPaths.some((path: string) => to.path.startsWith(path))) {
    ElMessage.error('权限不足，无法访问该页面');
    next(false);
    return;
  }

  next();
});

export default router;